﻿using SHZY.Common.Core.Manager;
using SHZY.Common.Core.Security;
using SHZY.ClayObject;
using SHZY.Common.Configuration;
using SHZY.Common.Models.NPOI;
using SHZY.DataEncryption;
using SHZY.Common.Enum;
using SHZY.Common.Extension;
using SHZY.Common.Filter;
using SHZY.Common.Models;
using SHZY.Common.Security;
using SHZY.DependencyInjection;
using SHZY.DynamicApiController;
using SHZY.FriendlyException;
using SHZY.Systems.Entitys.Permission;
using SHZY.Systems.Entitys.System;
using SHZY.Systems.Interfaces.System;
using SHZY.system.Entitys.Dto.QmsBaseInnspectionentry;
using SHZY.system.Entitys;
using SHZY.system.Interfaces;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace SHZY.system;

/// <summary>
/// 业务实现：检验条目.
/// </summary>
[ApiDescriptionSettings(Tag = "system", Name = "QmsBaseInnspectionentry", Order = 200)]
[Route("api/system/[controller]")]
public class QmsBaseInnspectionentryService : IQmsBaseInnspectionentryService, IDynamicApiController, ITransient
{
    /// <summary>
    /// 服务基础仓储.
    /// </summary>
    private readonly ISqlSugarRepository<QmsBaseInnspectionentryEntity> _repository;

    /// <summary>
    /// 多租户事务.
    /// </summary>
    private readonly ITenant _db;

    /// <summary>
    /// 数据接口服务.
    /// </summary>
    private readonly IDataInterfaceService _dataInterfaceService;

    /// <summary>
    /// 用户管理.
    /// </summary>
    private readonly IUserManager _userManager;

    /// <summary>
    /// 初始化一个<see cref="QmsBaseInnspectionentryService"/>类型的新实例.
    /// </summary>
    public QmsBaseInnspectionentryService(
        ISqlSugarRepository<QmsBaseInnspectionentryEntity> qmsBaseInnspectionentryRepository,
        IDataInterfaceService dataInterfaceService,
        ISqlSugarClient context,
        IUserManager userManager)
    {
        _repository = qmsBaseInnspectionentryRepository;
        _dataInterfaceService = dataInterfaceService;
        _db = context.AsTenant();
        _userManager = userManager;
    }

    /// <summary>
    /// 获取检验条目.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<dynamic> GetInfo(string id)
    {
        return (await _repository.FirstOrDefaultAsync(x => x.Id == id)).Adapt<QmsBaseInnspectionentryInfoOutput>();
    }

    /// <summary>
    /// 获取检验条目列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("")]
    public async Task<dynamic> GetList([FromQuery] QmsBaseInnspectionentryListQueryInput input)
    {
        var data = await _repository.Context.Queryable<QmsBaseInnspectionentryEntity>()
            .WhereIF(!string.IsNullOrEmpty(input.innspectionName), it => it.InnspectionName.Contains(input.innspectionName))
            .WhereIF(!string.IsNullOrEmpty(input.keyword), it => it.InnspectionName.Contains(input.keyword))
            .OrderByIF(string.IsNullOrEmpty(input.sidx), it => it.Id)
            .Select(it => new QmsBaseInnspectionentryListOutput
            {
                id = it.Id,
                innspectionName = it.InnspectionName,
                enabledMark = SqlFunc.IIF(it.EnabledMark == 0, "无效", "有效"),
            }).OrderByIF(!string.IsNullOrEmpty(input.sidx), it => input.sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
        return PageResult<QmsBaseInnspectionentryListOutput>.SqlSugarPageResult(data);
    }

    /// <summary>
    /// 新建检验条目.
    /// </summary>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPost("")]
    public async Task Create([FromBody] QmsBaseInnspectionentryCrInput input)
    {
        var entity = input.Adapt<QmsBaseInnspectionentryEntity>();
        entity.Id = SnowflakeIdHelper.NextId();
        var isOk = await _repository.Context.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
        if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1000);
    }

    /// <summary>
    /// 获取检验条目无分页列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    private async Task<dynamic> GetNoPagingList([FromQuery] QmsBaseInnspectionentryListQueryInput input)
    {
        return await _repository.Context.Queryable<QmsBaseInnspectionentryEntity>()
            .WhereIF(!string.IsNullOrEmpty(input.innspectionName), it => it.InnspectionName.Contains(input.innspectionName))
            .WhereIF(!string.IsNullOrEmpty(input.keyword), it => it.InnspectionName.Contains(input.keyword))
            .OrderByIF(string.IsNullOrEmpty(input.sidx), it => it.Id)
            .Select(it => new QmsBaseInnspectionentryListOutput
            {
                id = it.Id,
                innspectionName = it.InnspectionName,
                enabledMark = SqlFunc.IIF(it.EnabledMark == 0, "无效", "有效"),
            }).OrderByIF(!string.IsNullOrEmpty(input.sidx), it => input.sidx + " " + input.sort).ToListAsync();
    }

    /// <summary>
    /// 导出检验条目.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("Actions/Export")]
    public async Task<dynamic> Export([FromQuery] QmsBaseInnspectionentryListQueryInput input)
    {
        var exportData = new List<QmsBaseInnspectionentryListOutput>();
        if (input.dataType == 0)
            exportData = Clay.Object(await GetList(input)).Solidify<PageResult<QmsBaseInnspectionentryListOutput>>().list;
        else
            exportData = await GetNoPagingList(input);
        List<ParamsModel> paramList = "[{\"value\":\"检验条目名称\",\"field\":\"innspectionName\"},{\"value\":\"有效标志\",\"field\":\"enabledMark\"},]".ToList<ParamsModel>();
        ExcelConfig excelconfig = new ExcelConfig();
        excelconfig.FileName = "检验条目.xls";
        excelconfig.HeadFont = "微软雅黑";
        excelconfig.HeadPoint = 10;
        excelconfig.IsAllSizeColumn = true;
        excelconfig.ColumnModel = new List<ExcelColumnModel>();
        foreach (var item in input.selectKey.Split(',').ToList())
        {
            var isExist = paramList.Find(p => p.field == item);
            if (isExist != null)
                excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value });
        }

        var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
        ExcelExportHelper<QmsBaseInnspectionentryListOutput>.Export(exportData, excelconfig, addPath);
        var fileName = _userManager.UserId + "|" + addPath + "|xls";
        return new
        {
            name = excelconfig.FileName,
            url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "SHZY")
        };
    }

    /// <summary>
    /// 批量删除检验条目.
    /// </summary>
    /// <param name="ids">主键数组.</param>
    /// <returns></returns>
    [HttpPost("batchRemove")]
    public async Task BatchRemove([FromBody] List<string> ids)
    {
        var entitys = await _repository.Context.Queryable<QmsBaseInnspectionentryEntity>().In(it => it.Id, ids).ToListAsync();
        if (entitys.Count > 0)
        {
            try
            {
                // 开启事务
                _db.BeginTran();

                // 批量删除检验条目
                await _repository.Context.Deleteable<QmsBaseInnspectionentryEntity>().In(it => it.Id,ids).ExecuteCommandAsync();

                // 关闭事务
                _db.CommitTran();
            }
            catch (Exception)
            {
                // 回滚事务
                _db.RollbackTran();

                throw Oops.Oh(ErrorCode.COM1002);
            }
        }
    }

    /// <summary>
    /// 更新检验条目.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPut("{id}")]
    public async Task Update(string id, [FromBody] QmsBaseInnspectionentryUpInput input)
    {
        var entity = input.Adapt<QmsBaseInnspectionentryEntity>();
        var isOk = await _repository.Context.Updateable(entity).UpdateColumns(it => new 
        {
            it.InnspectionName,
            it.EnabledMark,
        }).ExecuteCommandAsync();
        if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1001);
    }

    /// <summary>
    /// 删除检验条目.
    /// </summary>
    /// <returns></returns>
    [HttpDelete("{id}")]
    public async Task Delete(string id)
    {
        var isOk = await _repository.Context.Deleteable<QmsBaseInnspectionentryEntity>().Where(it => it.Id.Equals(id)).ExecuteCommandAsync();
        if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1002);
    }
}